package com.wlr.blog.web.common.service.impl;

import cn.hutool.core.lang.Assert;
import com.wlr.blog.util.common.exception.CustomException;
import com.wlr.blog.web.common.dto.MailRequest;
import com.wlr.blog.web.common.service.SendMailService;
import com.wlr.blog.web.common.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author lrwang
 * @version 1.0
 * @date 2022/12/7 13:52
 */
@Service
@Slf4j
public class SendMailServiceImpl implements SendMailService {
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username:null}")
    private String sendMailer;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void checkMail(MailRequest mailRequest) {
        Assert.notNull(mailRequest, "邮件请求不能为空");
        Assert.notNull(mailRequest.getSendTo(), "邮件收件人不能为空");
        Assert.notNull(mailRequest.getSubject(), "邮件主题不能为空");
        Assert.notNull(mailRequest.getText(), "邮件内容不能为空");
    }

    @Override
    public void sendSimpleMail(MailRequest mailRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        checkMail(mailRequest);
        message.setFrom(sendMailer);
        message.setTo(mailRequest.getSendTo().split(","));
        message.setSubject(mailRequest.getSubject());
        message.setText(mailRequest.getText());
        message.setSentDate(new Date());
        javaMailSender.send(message);
        log.info("发送邮件成功：{}->{}", sendMailer, mailRequest.getSendTo());
    }

    @Override
    public void sendHtmlMail(MailRequest mailRequest) {

    }

    @Override
    public void sendVerifyCode(MailRequest mailRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        checkMail(mailRequest);
        message.setFrom(sendMailer);
        message.setTo(mailRequest.getSendTo().split(","));
        message.setSentDate(new Date());
        message.setText(mailRequest.getText());
        String verifyCode = MailUtils.generateCode(4);

        try {
            redisTemplate.opsForValue().set(Arrays.toString(mailRequest.getSendTo().split(",")) + "#register", verifyCode, 5, TimeUnit.MINUTES);
            javaMailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("验证码发送失败！");
        }
    }
}
